import json
from datetime import datetime

import pytz
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated

from Group.models import MemberTraining, TeamMemberShip
from Group.permission import IsTeamMember, IsTeamMemberSelfOrAdmin, IsInLab301
from Group.serializers import TeamMemberTrainSerializer, TeamMemberSelfTrainViewSerializer, TeamMemberSignInSerializer, \
    TeamMemberRemarkSerializer
from Person.authenticate import MyJSONWebTokenAuthentication
from Utils.BaseResponse import BaseResponse


class TeamMemberTrainListView(generics.ListAPIView):
    serializer_class = TeamMemberTrainSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated, IsTeamMember]

    def get_queryset(self, *args, **kwargs):
        # 获取当日的所有训练
        team_id = self.kwargs.get('pk')
        today = datetime.now().date()
        today_weekday = today.weekday() + 1

        if self.request.query_params.get('all') == 'true':
            return MemberTraining.objects.filter(team_id=team_id)

        records = MemberTraining.objects.filter(
            team_id=team_id,
            start_time__date__lte=today,
            end_time__date__gte=today
        )
        # 再检查所有 records 的 recurrence_days
        filtered_records = []
        for record in records:
            if record.training_type == 0:  # 定期训练
                recurrence_days = json.loads(record.recurrence_days)
                if today_weekday in recurrence_days:
                    filtered_records.append(record)
            elif record.training_type == 1:  # 单次训练
                if record.start_time.date() == today:
                    filtered_records.append(record)

        return filtered_records

    def get(self, *args, **kwargs):
        """
            团队成员训练，返回团队当日的所有训练成员
        """
        response = super().get(*args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(data={"list": response.data}, status=200).success()
        return BaseResponse(data=response.data, status=response.status_code).fail()


class TeamMemberSelfTrainView(generics.ListAPIView, generics.CreateAPIView):
    serializer_class = TeamMemberSelfTrainViewSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated, IsTeamMemberSelfOrAdmin]

    def get_queryset(self, *args, **kwargs):
        team_id = self.kwargs.get('pk')
        member = TeamMemberShip.objects.get(person_id=self.request.user.id, team_id=team_id)
        if self.request.query_params.get('all'):
            return MemberTraining.objects.filter(team_id=team_id, member=member).order_by('id')
        today = datetime.now().date()
        records = MemberTraining.objects.filter(team_id=team_id, start_time__date__lte=today, member=member,
                                                end_time__date__gte=today).order_by('start_time')
        queryset = []
        for record in records:
            if record.training_type == 0:  # 定期训练
                recurrence_days = json.loads(record.recurrence_days)
                if today.weekday() + 1 in recurrence_days:
                    queryset.append(record)
            elif record.training_type == 1:  # 单次训练
                queryset.append(record)
        return queryset

    def get(self, *args, **kwargs):
        """
            返回团队团员当天的所有训练，有当天或者全部
            all = false 当天所有训练
            all = true 用户所有训练
        """
        response = super().get(*args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(data={"list": response.data, "count": len(response.data)},
                                status=200).success()

        return BaseResponse(data=response.data, status=response.status_code).fail()

    def post(self, *args, **kwargs):
        """
            创建团队成员训练
        """
        response = super().post(*args, **kwargs)
        if response.status_code == 201:
            return BaseResponse(data=response.data, status=201).success()
        return BaseResponse(data=response.data, status=response.status_code).fail()


class TeamMemberSignInView(generics.CreateAPIView, generics.ListAPIView):
    """
        get：返回用户的当前需要签到的任务，以及是否签到，今天是否有训练任务
            needTrain: bool
            train: {
                name:
                begin_time:
                end_time:
                status: 4
            }
        post：用户请求签到，或者请假

    """
    authentication_classes = [MyJSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated, IsTeamMemberSelfOrAdmin, IsInLab301]

    def get_queryset(self, *args, **kwargs):
        team_id = self.kwargs.get("pk")
        member = TeamMemberShip.objects.get(person=self.request.user, team_id=team_id)
        today = datetime.now().date()
        now = datetime.now(pytz.timezone('Asia/Shanghai')).time()

        # 查询符合条件的训练
        records = MemberTraining.objects.filter(
            team_id=team_id,
            member=member,
            start_time__date__lte=today,
            end_time__date__gte=today
        ).order_by('start_time')

        queryset = []
        for record in records:
            if record.training_type == 0:  # 定期训练
                recurrence_days = json.loads(record.recurrence_days)
                # 检查今天是否在 recurrence_days 中
                if today.weekday() + 1 in recurrence_days:
                    # 判断当前时间是否在训练时间范围内
                    if record.start_time.time() <= now <= record.end_time.time():
                        queryset.append(record)
            elif record.training_type == 1:  # 单次训练
                # 判断当前时间是否在训练时间范围内
                if record.start_time.date() == today and record.start_time.time() <= now <= record.end_time.time():
                    queryset.append(record)
        return queryset

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method == 'GET':
            return TeamMemberSelfTrainViewSerializer  # 替换为GET请求的序列化器
        elif self.request.method == 'POST':
            return TeamMemberSignInSerializer
        return super().get_serializer_class()

    def get(self, *args, **kwargs):
        """
            返回团队团员当天的所有训练，有当天或者全部
            all = false 当天所有训练
            all = true 用户所有训练
        """
        response = super().get(*args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(data={"list": response.data, "count": len(response.data)},
                                status=200).success()

        return BaseResponse(data=response.data, status=response.status_code).fail()

    def post(self, *args, **kwargs):
        """
            团队成员签到
        """
        response = super().post(*args, **kwargs)
        if response.status_code == 201:
            return BaseResponse(data=response.data, status=201).success()
        return BaseResponse(data=response.data, status=response.status_code).fail()


class TeamMemberRemarkView(generics.UpdateAPIView):
    authentication_classes = [MyJSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated, IsTeamMemberSelfOrAdmin, ]
    serializer_class = TeamMemberRemarkSerializer

    def get_queryset(self):
        return TeamMemberShip.objects.filter(team_id=self.kwargs.get("pk"))

    def get_object(self, *args, **kwargs):
        try:
            member = self.get_queryset().get(person=self.request.user, team_id=self.request.data.get("id"))
        except TeamMemberShip.DoesNotExist:
            member = self.get_queryset().get(person=self.request.user, team_id=self.kwargs.get("pk"))
        return member

    def patch(self, request, *args, **kwargs):
        response = super().patch(request, *args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(response.data, status=response.status_code).success()
        return BaseResponse(response.data).fail()

    def put(self, request, *args, **kwargs):
        response = super().put(request, *args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(response.data, status=response.status_code).success()
        return BaseResponse(response.data).fail()
